package com.litchi.pools;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: Jiangxx
 * @Date: 2023/10/18
 * @Description:
 */
public class CustomThreadFactory implements ThreadFactory {
    /**
     * 线程池数量
     */
    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
    private final ThreadGroup group;

    /**
     * 线程数量
     */
    private final AtomicInteger THREAD_NUMBER = new AtomicInteger(1);
    private final String threadTag;

    public CustomThreadFactory(String threadTag) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.threadTag = "POOL-" + POOL_NUMBER.getAndIncrement() + "-" + threadTag + "-";
    }

    @Override
    public Thread newThread(Runnable target) {
        Thread result = new Thread(group, target, threadTag + THREAD_NUMBER.getAndIncrement(), 0);
        if (result.isDaemon()) {
            result.setDaemon(false);
        }
        if (result.getPriority() != Thread.NORM_PRIORITY) {
            result.setPriority(Thread.NORM_PRIORITY);
        }
        return result;
    }
}
